#!/usr/bin/perl
#
# Display info about a Person, with the option to
# edit, and to push lots of buttons to do things with his Place.
#
use LinuxCounter;
use FileTable;
use Fcntl;
use Counter::CGI;
use ErrorForm;
use CounterCGI;
use Validate::Places;
use Validate::Persons;
use Counter;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$q = new Counter::CGI;
$users = Counter::open(O_RDONLY);
$persons = Counter::openfile("persons");
$places = Counter::openfile("places");

$key = $q->param('user');
if ($key =~ /@/) {
    $userrec = $users->getbyemail($key);
} else {
    $userrec = $users->get($key);
}
if (!$userrec) {
    errorForm("No user record for $key");
}
$key = $userrec->key();
$rec = $persons->getclean($key);
$rawrec = $persons->get($rec->key) if $rec;
# see if patching is wanted
if ($rawrec && $q->param("patchfield")) {
    $patchfield = $q->param("patchfield");
    $value = $q->param("patchvalue");
    $oldvalue = $rawrec->{$patchfield};
    if (defined($value)) {
	$rawrec->{$patchfield} = $value;
    } else {
	delete $rawrec->{$patchfield};
    }
    $rawrec->store();
}
print <<EoF;
Content-type: text/html; charset="utf-8"

<html>
EoF
CounterCGI::pagehead("Admin information for $key");
print "<body bgcolor=\"white\">\n";
CounterCGI::pagetop($q);
if ($patchfield) {
    print "<em>Changed $patchfield from \"$oldvalue\" to \"$value\"</em>\n";
}

if (!$rec) {
    print <<EoF;
<h1><img src="/cgi-bin/certificate.cgi/$key"
    alt="Registered Linux User #$key" align=middle> (no person record)</h1>
EoF
    admininfo();
} else {
    print <<EoF;
<h1><img src="/cgi-bin/certificate.cgi/$key"
    alt="Registered Linux User #$key" align=middle> $$rec{name}</h1>
<p>
EoF
    admininfo();
    print "<table border><tr><td>\n"; # table around personinfo
    print "<b>Person info<br>(as entered)</b>\n";
    print "</td><td><b>Associated emails</b>\n";
    print "<tr><td>";
    printPersonTable($rawrec);
    print "</td><td>\n";
    print "<table>\n"; # table of emails
    print "<tr><th>Use</th><th>Email</th><th>State</th>\n";
    @emails = $userrec->emails();
    for $mail (sort {$$a{usage} cmp $$b{usage}} @emails) {
        my $my_email = htmlquote($mail->key());
        $my_email =~ s/@/&#x40;/g;
	print "<tr><td>$$mail{usage}</td><td>",
	        $my_email, "</td><td>$$mail{state}</td></tr>\n";
    }
    print "</table>\n"; # table of emails
    print "</table>\n"; # table around personinfo
    print <<EoF;
<p>
The record ID is $key<br>
Record last updated: $$rec{recdate}<br>
EoF
} # end user record present

print <<EoF;
<form method=post action="/cgi-bin/adm/show-user.cgi">
<input type=hidden name="key" value=$key>
<input type="submit" value="Update">
</form>
<form method=post action="/cgi-bin/adm/merge.cgi">
Merge with key <input name="key2" size=10>
<input type=hidden name="key" value=$key>
<input type="submit" value="Merge">
</form>

EoF
if ($rec) {
   print "<hr>\n<h2>Place info</h2>\n";

#
# Print place info, with lots of interesting buttons and input fields
# to change it if it doesn't look perfect.
#

    ($country, $state, $city, $myplace) = Validate::Places::findplaces($rawrec);
    print "The place ID for this record is $$myplace{name}<p>\n";
    $placesource = $rec->{placesource};
    if ($$myplace{name} ne $$rec{placeid}) {
	$rawrec->clean();
	print "This isn't the same as what's in the record; the record has been cleaned. Please push Reload.<p>\n";
    } elsif ($placesource eq "clean-email") {
	print "This guy got his placement in the places tree based on his email address, which probably means some of his basic attributes (like country) were blank or wrong. The code to make sense of this situation isn't here yet - look at the stuff below and then press the \"update\" button above.<p>\n";
	print "<table border><tr><th>Field<th>Entered<th>Interpreted\n";
	for $field (qw(country state city)) {
	    print "<tr><td>$field<td>", $rawrec->{$field}, "<td>",
	    $rec->{$field}, "\n";
	}
	print "</table>\n";
	$myself = $q->self_url();
	print "<a href=\"/cgi-bin/adm/display-person.cgi?user=$key&patchfield=country&patchvalue=$$rec{country}\">";
	print "Place computed country into record</a>";
    } elsif ($placesource ne "clean-placename" 
	     && $placesource ne "clean-alias") {
	print "The place ID was determined by $placesource. Take care.<p>\n";
    } else { # placename & alias go here
	if ($placesource eq "clean-alias") {
	    print "The alias $$rec{placealias} was used " 
		. "to find this person's place<p>\n";
	}
	if ($country->{type} ne "country") {
	    print "Country $$rec{country} isn't listed in the places DB?<br>\n";
	}
	if ($rec->{state} && !$state) {
	    print "State $$rec{state} isn't listed in the places DB?<br>\n";
	}
	if ($rec->{city} && !$city) {
	    print "City $$rec{city} isn't listed in the places database<br>\n";
	    print "You may want to take one of the actions listed below<br>\n";
	    $trythis = substr($$rec{city}, 0, 3);
	    if ($myplace->{type} eq "state") {
		$searchscope = "$$myplace{name}";
		$namecontext = "$$myplace{name}";
	    } else {
		$searchscope = "$$myplace{name}:%";
		$namecontext = "$$myplace{name}:";
	    }
	    $asciified = Validate::Places::namecase($$rec{city});
            my $placekey = $myplace->key();
	    print <<EoF;
<hr>
<form method="POST" action="addform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="wwws/adm/placerec.php">
<!-- Values for the new record -->
<input type=hidden name="within" value="$placekey">
<input type=hidden name="type" value="city">
<input type=hidden name="name" value="$namecontext:$asciified">
<input type=hidden name="longname" value="$$rec{city}">
Declare $$rec{city} to be a valid city under $$myplace{name}
<input type="submit" value="Do it!">
</form>
<hr>
EoF

            while ($trythis ne "") {
		chop $trythis;
		warn "Trying search for $searchscope:$trythis\n";
		@placeshere = $places->select("(name like '$searchscope:$trythis%'"
					  . " or name like '%:$$rec{city}')"
					  . " and type = 'city' order by name");
		last if @placeshere + 0 >= 3; 
	    }
	    if (@placeshere + 0 > 0) {
		print "Places that might fit:\n<ul>";
		for $place (@placeshere) {
		    print "<li>", $place->{name}, " <i>", $place->{longname}, "</i>\n";
		}
		print <<EoF;
</ul>
<form method="POST" action="addform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="wwws/adm/placerec.php">
<!-- Values for the new record -->
<input type=hidden name="type" value="alias">
<input type=hidden name="name" value="$namecontext:$asciified">
<input type=hidden name="longname" value="$$rec{city}">
Declare $$rec{city} an alias for
<select name="within">
EoF
                for $place (@placeshere) {
		    my $placekey = $place->key();
		    print "<option value=\"$placekey\">$$place{name}\n";
		}
		print "</select>\n";
		print "<input type=\"submit\" value=\"Do it!\">\n</form>\n";
		
	    }
	}
    }
} # if $rec
# 

print <<EoF;
<hr>
Contact: <a href="mailto:webmaster&#x40;counter.li.org">Webmaster&#x40;counter.li.org</a>
<br>
</body>
</html>
EoF

sub admininfo {
# Print admin info from userrec
my $my_email = $$userrec{email};
$my_email =~ s/@/&#x40;/g;

print <<EoF;
<table cellpadding=0>
<tr><td>State<td>$$userrec{state}
<tr><td>Contact email<td>$my_email
<tr><td>Login time<td>$$userrec{logintime}
    <tr><td>Created<td>$$userrec{f_ctime}
    <tr><td>Modified<td>$$userrec{f_mtime}
EoF
    if ($$userrec{login}) {
	print "<tr><td>Login name<td>$$userrec{login}\n";
    }
    if ($$userrec{comment}) {
	print "<tr><td>Comment<td>$$userrec{comment}\n";
    }
    print "</table>\n";
}

